﻿using Microsoft.Reporting.WinForms;
using Sunny.UI;
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Windows.Forms;
using WebAssistant.BusinessLogic;
using WebAssistant.Common;
using static Assistant.Controllers.PrintModel;

namespace Assistant.Report.Preview
{

    public partial class FormPreview : UIForm        
    {
        private readonly ReportViewer reportViewer;
        readonly static string ReportFolderPath = AppDomain.CurrentDomain.BaseDirectory + @"\Report\Rdlc\";
        public static FormPreview previewForm;
        

        public FormPreview()
        {
            InitializeComponent();            
            InitializeOdoo();
            previewForm = this;

            reportViewer = new ReportViewer();
            reportViewer.Dock = DockStyle.Fill;
            Controls.Add(reportViewer);
        }


        public void ReceivingPrintData(PrintAction printAction)
        {
            InitializeReportViewer(printAction);
        }


        private void InitializeOdoo()
        {
            
            string[] ConfigKeyList = new string[] {
                "odoo.server.url", "odoo.server.database", "odoo.server.user", "odoo.key", "odoo.server.password"
            };
            foreach (string configkey in ConfigKeyList)
            {
                if (!DataAccess.CheckSettingExists(configkey))
                {
                    ShowWarningDialog("Odoo服务器配置错误！请设置。");
                    return;
                }
            }            
        }

        private void InitializeReportViewer(PrintAction printAction)
        {
            this.Text += "-" + printAction.Name;
            string className = OdooRpcClient.Converters.ModelMapper.GetModelName(printAction.Context.active_model)[0];
            //string fullName = OdooRpcClient.Converters.ModelMapper.GetModelName(printAction.context.active_model)[1];
            //string assemblyName = OdooRpcClient.Converters.ModelMapper.GetModelName(printAction.context.active_model)[2];

            string reportName = printAction.ReportName;
            string reportPath = ReportFolderPath + reportName + ".rdlc";
            //string reportPath = ReportFolderPath + reportName + ".rdl";

            reportViewer.LocalReport.EnableExternalImages = true;
            reportViewer.ZoomMode = ZoomMode.Percent;
            //页边距
            System.Drawing.Printing.PageSettings newPageSettings = new System.Drawing.Printing.PageSettings();
            newPageSettings.Margins = new System.Drawing.Printing.Margins(10, 10, 10, 10);
            reportViewer.SetPageSettings(newPageSettings);
            //设置打印布局模式,显示物理页面大小
            reportViewer.SetDisplayMode(DisplayMode.PrintLayout);
            //缩放模式为百分比,以100%方式显示
            reportViewer.ZoomPercent = 100;

            if (className == null)
            {
                ShowErrorDialog("无法生成报表! \n" + "尚未添加该模型[" + printAction.Context.active_model + "]\n请联系开发者");
            }
            else
            {
                RenderReport(printAction, reportPath);
            }
        }

        public async void RenderReport(PrintAction printAction, string reportPath)
        {
            var loginResult = await Shared.odooClient.LoginAsync();
            ShowWaitForm("正在加载数据，请稍候...");
            ArrayList dataSetNames = ReportHelper.GetDataSetName(reportPath); //获取RDLC报表中：数据集名称

            if (loginResult.Succeed)
            {
                //string dataSetName = ReportHelper.GetDataSetName(reportPath); //获取RDLC报表中：数据集名称
                //报表数据
                using FileStream fs = new FileStream(reportPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                reportViewer.LocalReport.LoadReportDefinition(fs);

                DataSet ds = await ReportAction.GetReportDataTable<DataSet>(printAction);
                //string info = "";
                //foreach(DataTable dt in ds.Tables)
                //{
                //    info += dt.TableName + "\n";
                //}
                //ShowInfoDialog(info);
                foreach(DataTable dt in ds.Tables)
                {                  
                    if (dataSetNames.Contains(dt.TableName))
                    {
                        //报表数据
                        reportViewer.LocalReport.DataSources.Add(new ReportDataSource(dt.TableName, dt));
                    }
                    else if(dt.TableName== "Parameters")
                    {
                        //报表参数
                        //遍历报表参数名称,生成报表参数
                        foreach (DataColumn paramete in dt.Columns)
                        {
                            PreviewReportParameters item = new PreviewReportParameters();
                            item.Name = paramete.ColumnName;
                            item.Value = dt.Rows[0][paramete.ColumnName].ToString();
                            reportViewer.LocalReport.SetParameters(
                                new ReportParameter(paramete.ColumnName, dt.Rows[0][paramete.ColumnName].ToString())
                                );
                        }
                    }
                }

                //DataTable reportData = ds.Tables[0];
                
                reportViewer.LocalReport.DisplayName = printAction.Name;

                reportViewer.RefreshReport();
                
                HideWaitForm();
            }
            else
            {
                HideWaitForm();
                ShowInfoDialog("登陆验证失败，请检查配置是否正确");
            }
        }

        public class PreviewReportParameters
        {
            public string Name { get; set; }

            public string Value { get; set; }


        }

        private void FormPreview_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.Hide();
            this.DialogResult = DialogResult.OK;
        }

        
    }
}
